#include <math.h>
#include <stdlib.h>
#include "Device.h"
#include "SoftRederLib.h"
#include "Debug.h"
Device* dev;
SoftRederLib* lib;
typedef struct _Point{
	int x;
	int y;
} Point;


void setPixel(int x,int y)
{
	dev->DrawPixel(x, y, 1, 0, 0);
}

//inline int round(const float a) { return int(a + 0.5f); }

void lineDDA(int x1,int y1,int x2,int y2)
{
	int dx = x2 - x1, dy = y2 - y1, steps = 0;
	float xIncrement = 0, yIncrement = 0, x = x1, y = y1;
	if(abs(dx) > abs(dy)){
		steps = abs(dx);
	}else{
		steps = abs(dy);
	}
	xIncrement = (float)dx / (float)steps;
	yIncrement = (float)dy / (float)steps;
	setPixel(round(x), round(y));
	for (int k = 0; k < steps;k++)
	{
		x += xIncrement;
		y += yIncrement;
		setPixel(round(x), round(y));
	}
}

void polyline(Point* points,int n)
{
	if(n == 1){
		setPixel(points[0].x, points[0].y);
		return;
	}
	for (int i = 0; i < n-1;i++)
	{
		Point p1 = points[i];
		Point p2 = points[i + 1];
		lineDDA(p1.x, p1.y, p2.x, p2.y);
	}
}



void displayFunc()
{
	//Point points[6] = { { 125, 100 },
	//{ 150, 200 },
	//{ 175, 100 },
	//{ 100, 150 },
	//{ 200, 150 },
	//{ 125, 100 }
	//};
	//
	dev->ClearBuffer();
	//polyline(points, 6);
	for (int i = 0; i < 500;i++)
	{
		int x0 = rand() % 1000 + 0;
		int y0 = rand() % 1000 + 0;
		int x1 = rand() % 1000 + 0;
		int y1 = rand() % 1000 + 0;
		float r = (rand() % 1000 + 1)/1000.0f;
		float g = (rand() % 1000 + 1) / 1000.0f;
		float b = (rand() % 1000 + 1) / 1000.0f;
		Vector2 pStart = Vector2(x0, y0);
		Vector2 pEnd = Vector2(x1, y1);
		Vector2 nStart;
		Vector2 nEnd;
		Rect clipRect = Rect(100, 100, 400, 300);
		int ret = lib->ClipLine(pStart, pEnd, clipRect, nStart, nEnd);
		if(ret!=0){
			lib->DrawLine(nStart, nEnd, Color(r, g, b));
		}
		
	}
	dev->Flip();
	//Debug::Log("==============Start===============\n");
}

int main(int argc, char** argv)
{
	Debug::Log("==============Start===============\n");
	dev = new Device();
	dev->init(&argc, argv, 800, 600, "Test",displayFunc);
	lib = new SoftRederLib();
	lib->Init(dev);
	dev->run();
}